#include<iostream>
#include<cstdio>
#include<pthread.h>
#include<vector>
#include<string>
#include<unistd.h>
#include<cstdlib>

using namespace std;

#define NUM 5

//任务类
class Task 
{
public:
    Task(){ }

    ~Task(){ }

    void SetData(int x, int y) 
    {
        _x = x;
        _y = y;
    }

    int Add()
    {
        return _x + _y;
    }

private:
    int _x;
    int _y;
};

//线程类
class Thread
{
public:
    Thread(int x, int y, const string& threadname)
        :_threadname(threadname)
        { 
           _t.SetData(x, y); 
        }

    string& Threadname()
    {
        return _threadname;
    }

    int Run()
    {
        return _t.Add();
    }

    ~Thread(){ }

private:
    string _threadname; //名字
    Task _t;  //任务
};

//任务结果类
class Result
{
public:
    Result(const string& threadname, int result)
        :_threadname(threadname), _result(result)
        { }
    
    void print()
    {
        cout << _threadname << ": " << _result << endl;
    }

private:
    string _threadname;
    int _result;
};

void* handerTask(void* args)
{
    Thread* td = static_cast<Thread*>(args); //类型转换

    const string& threadname = td->Threadname();
    int result = td->Run();
    Result* res = new Result(threadname, result);

    delete td;
    return res;
}

int main()
{
    vector<pthread_t> id;
    vector<Result*> res;

    for(int i = 1; i <= NUM; i++)
    {
        char threadname[128];
        snprintf(threadname, sizeof(threadname), "Thread-%d", i);
        Thread* td = new Thread(10, 20, threadname);

        pthread_t tid;
        //创建新线程,参数和返回值为自定义类对象
        pthread_create(&tid, nullptr, handerTask, td); 
        id.push_back(tid);
    }

    for(auto& e : id)
    {
        void* tmp = nullptr;
        pthread_join(e, &tmp); //获取新线程的返回值(执行情况)
        res.push_back((Result*)tmp);
    }

    for(auto& e : res)
    {
        e->print();
        delete e;
    }

    return 0;
}